import axios from 'axios'
// 1.1 sore/cart.js新建cart模块
export default {
  // 1.2开启命名空间
  namespaced: true,
  state: {
    list: []
  },
  getters: {
    // 计算总数量
    totalCount (state) {
      return state.list.reduce((pre, item) => pre + item.count, 0)
    },
    // 计算总价格
    totalPrice (state) {
      return state.list.reduce((pre, item) => pre + item.count * item.price, 0)
    }

  },
  // 4、定义函数修改数据
  mutations: {
    saveList (state, payload) {
      state.list = payload
    }
  },
  // 3、定义函数请求数据
  actions: {
    async loadData (store) {
      const res = await axios({ url: 'http://localhost:3000/cart' })
      console.log('res--->', res)
      // 5、调用函数修改数据
      store.commit('saveList', res.data)
    }
  }
}
